<template>
  <div id="login-container">
    <div id="login-box">
      <div id="avatar-box">
        <img src="../assets/img/logo.png" alt />
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRule">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username"  placeholder="请输入用户名" >
            <i slot="prefix" class="iconfont icon-icon-user"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" show-password placeholder="请输入密码">
            <i slot="prefix" class="iconfont icon-mobile"></i>
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :push='14'>
            <el-button type="primary" @click="login()">确定</el-button>
            <el-button type="info" @click="$refs.loginFormRef.resetFields()">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRule: {
        username: [
          { required: true, message: '用户名必填', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]

      }
    }
  },
  methods: {
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (valid === true) {
          // axios访问服务器 校验 用户名 和 密码 是否有效
          const { data: res } = await this.$http.post('/login', this.loginForm)
          if (res.meta.status !== 200) {
            return this.$message.error('用户名或密码不存在')
          }

          // 通过浏览器的sessionStorage记录服务器返回的token信息
          window.sessionStorage.setItem('token', res.data.token)

          this.$router.push('/home')
        }
      })
    }

  }

}
</script>

<style lang="less" scoped>
#login-container {
  background-color: #2b4b6b;
  height: 100%;
  overflow: hidden;
  #login-box {
    width: 450px;
    height: 304px;
    background-color: #fff;
    border-radius: 4px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .el-form {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 20px;
      box-sizing: border-box;
    }
  }
  #avatar-box {
    width: 130px;
    height: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 8px;
    background-color: #fff;
    box-shadow: 0 0 10px #eee;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}
</style>
